package Callable;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class Test2 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //定义一个任务
        Callable<Integer> callable = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int sum = 0;
                for(int i = 1; i <= 1000; i++){
                    sum += i;
                }
                return sum;
            }
        };
        //任务不能直接传给线程，需要通过一个中间类FutureTask来传递
        FutureTask<Integer> task = new FutureTask<>(callable);
        //创建一个线程来执行
        Thread t1 = new Thread(task);
        t1.start();
        //获取计算结果，get方法可以阻塞等待call方法计算完毕,get才返回结果
        System.out.println("sum = " + task.get());
    }
}
